package core

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"strings"
	"time"
)

const difficulty = 1

type Block struct {
	Index        int64
	TimeStemp    int64
	PreBlockHash string
	Currhash     string
	Data         string
	Nonce        string
	Difficulty   int
}

func CreateBlockHash(b Block) string {
	hashData := string(b.Index) + string(b.TimeStemp) + b.PreBlockHash + b.Data + b.Nonce
	hashBytes := sha256.Sum256([]byte(hashData))
	hashComtent := hex.EncodeToString(hashBytes[:])
	return hashComtent
}
func CreateNewBlock(preBlock Block, data string) Block {
	newBlock := Block{}
	newBlock.Index = preBlock.Index + 1
	newBlock.TimeStemp = time.Now().Unix()
	newBlock.PreBlockHash = preBlock.Currhash
	newBlock.Data = data
	newBlock.Difficulty = difficulty
	for i := 0; ; i++ {
		hex := fmt.Sprintf("%x", i)
		fmt.Printf("hex 值为：%s\n", hex)
		newBlock.Nonce = hex
		if !isHashValid(CreateBlockHash(newBlock), newBlock.Difficulty) {
			fmt.Println(CreateBlockHash(newBlock), "没有挖中，继续挖矿！")
			//time.Sleep(time.Second)
			continue
		} else {
			fmt.Println(CreateBlockHash(newBlock), "恭喜挖矿成功！")
			newBlock.Currhash = CreateBlockHash(newBlock)
			break
		}
	}
	return newBlock
}

func isHashValid(hash string, difficulty int) bool {
	prefix := strings.Repeat("0", difficulty)

	return strings.HasPrefix(hash, prefix)
}

func GenerateGenesisBlock() Block {
	preBlock := Block{}
	preBlock.Index = 0
	preBlock.PreBlockHash = ""
	preBlock.Nonce = ""
	preBlock.TimeStemp = time.Now().Unix()
	preBlock.Data = "Genesis block"
	preBlock.Difficulty = difficulty
	preBlock.Currhash = CreateBlockHash(preBlock)
	return preBlock
}
